package mk.edu.ii.traval;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;

import android.widget.Button;

/**
 * This class is used for Main Activity of Traval Aplication
 * @author  G.K. N.A. M.A.
 */
public class MainTraval extends Activity {
	
	public static final String MYPREFS = "TravalPreferences";//name of the shared preferences
	public static final String PREF="Status";
	protected static final String NOTIFIKACIJA = new String("android.intent.action.NOTIFIKACIJA");
	public Double lat; // location latitude
	public Double lon; // location longitude
	public String radius; //area radius
	public boolean isActive; //status of the Alarm
	protected Spinner alertType; //choosen type of alert
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maintraval);
        
        //Get reference for UI widgets
        final TextView locText=(TextView)findViewById(R.id.locText);
        final TextView radiusText=(TextView)findViewById(R.id.radiusText);
        alertType= (Spinner)findViewById(R.id.spinner_alert_type);
    	final Button activateButton = (Button) findViewById(R.id.activateButton);
    	
    	final String name;
    	
    	//loading and setting last preferences
    	load();
    	set();
    	
        //get the Information from recevied Intent
        Intent startedFrom = this.getIntent();
        
        //hendle when we get call from Notifiaction
        if(startedFrom.getAction()!=null){
        	if(startedFrom.getAction().equals(NOTIFIKACIJA)){
        		//stop the Service
        		stopAlarm();
        		isActive=false;//set and load status
        		save();
        		load();
        		set();
        	}
        }
        
      	//get the Information from recevied Intent 
        lat = new Double(startedFrom.getDoubleExtra ("latitude",1000));
        lon = new Double(startedFrom.getDoubleExtra ("longitude",1000));
        name = startedFrom.getStringExtra("location");
        radius = startedFrom.getStringExtra("radius");
        
        //if we have correct locations we show the informations 
        if (lat.doubleValue() != 1000 && lon.doubleValue() != 1000)
        	{	
   	   	  		locText.setText(name);
   	   	  		radiusText.setText(radius+"meters");
   	   	  	}
        else{
        		// else we show location not selected yet
        		locText.setText("location not selected");
   	   	  		radiusText.setText("radius not selected");
        }
        //*********************************************
    	        
        //Get reference for "Change Destination Area" Button
        final Button destinationButton = (Button) findViewById(R.id.destinationButton);
        
        //starting onClick Listener for "Change Destination Area" Button  
        destinationButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v){
        	
        	//creating Intent for launching new Activity
        	Intent locationList = new Intent(v.getContext(),LocationListActivity.class);
        	
        	//starting LocationList Activity
	    	startActivity(locationList);
        }});
        
        //populating AlertType Spinner 
        populateSpinner(alertType);
        
        //starting onClick Listener for "Activate" button
        activateButton.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v){
        	check();
        }});       
    }
    /** Called when the activity is resumed. */
    @Override
    protected void onResume() {
    	Intent startedFrom=this.getIntent();
    	if(startedFrom.getAction()!=null){
        	if(startedFrom.getAction().equals(NOTIFIKACIJA)){
        		stopAlarm();
        		isActive=false;
        		save();
        		load();
        		set();
        	}
        }
    	super.onResume();
    }
    /** Called when the Menu for this Activity is first created. */
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
    	super.onCreateOptionsMenu(menu);
    	
    	//menu.add(0, 0, 0, "Home screen");
    	menu.add(0,0,1,"Destinations");
    	menu.add(0,1,2,"Alarm Types");
    	menu.add(0,2,3,"Minimize");
    	return true;
    } 

    /** Called when item form Menu is selected. */
    @Override
    public boolean onOptionsItemSelected(MenuItem item){
    	final  Spinner alertType = (Spinner)findViewById(R.id.spinner_alert_type);
     	super.onOptionsItemSelected(item);
    	switch (item.getItemId()) {
       	case 0:{
       		showDestinations();
       		return true;}
       	case 1:populateSpinner(alertType);
       		return true;
       	case 2://minimize service
       		return true;
       }
    	return true;
    }
    /** Called when we select Destinations from Menu. */
    public void showDestinations(){
    	Intent destinations=new Intent(this,LocationListActivity.class);
    	startActivity(destinations);
    }
    
    public void minimize(){
    	
    }
    
    /** saving the praferences that we have at the moment */
    
    public void save(){
    	SharedPreferences app_pref=getSharedPreferences(PREF, MODE_PRIVATE);
    	SharedPreferences.Editor editor2=app_pref.edit();
    	
    	editor2.putBoolean("sostojba",isActive);
    	editor2.commit();
    }

    /** Loading the preferences that we have last saved. */
    public void load(){
    	SharedPreferences app_pref = getSharedPreferences(PREF,MODE_PRIVATE);
    	Boolean statusot=app_pref.getBoolean("sostojba", true);
    	TextView statusenTextView=(TextView)findViewById(R.id.statusText);
    	if(statusot){
    		statusenTextView.setText("Alarm is activated");
    	}
    	else{
    		statusenTextView.setText("Alarm is deactivated");
    	}
    	isActive=statusot;
    }
    
    /** Checking if the service is started. */ 
    public void check(){
    	Button activateButton=(Button)findViewById(R.id.activateButton);
    	if(!isActive){
    		if(radius!=null){
    			activateButton.setText("Click to Deactivate");      
    			activateButton.setBackgroundResource(R.drawable.on);
    			startAlarm();
    			isActive=true;
    			save();
    			load();
        	}
    		else{
    			alertDialog();
    		}
    			
    	}
        	else{
        		activateButton.setText("Click to Activate");
        		activateButton.setBackgroundResource(R.drawable.off);
        		stopAlarm();// da se deaktivira alarmirajeto
        		isActive=false;
        		save();
        		load();
        	}
    }
    
    /** Seting button acording status. */ 
    public void set(){
    	Button activateButton=(Button)findViewById(R.id.activateButton);
        load();
    	if(isActive){
    		activateButton.setText("Click to Deactivate");      
        	activateButton.setBackgroundResource(R.drawable.on);
    		
    	}else{
    		activateButton.setText("Click to Activate");
    		activateButton.setBackgroundResource(R.drawable.off);
    		    		
    	}
    	
    }
    
    /** Populating spinner for Alert Type */
    private void populateSpinner(Spinner alertType) {
    	// Populate the update frequency spinner
    	ArrayAdapter<CharSequence> aAdapter;
    	aAdapter = ArrayAdapter.createFromResource(this,
    			R.array.Alert_types,android.R.layout.simple_spinner_item);
    	aAdapter.setDropDownViewResource(
    			android.R.layout.simple_spinner_dropdown_item);
    	alertType.setAdapter(aAdapter);
    	alertType.setSelection(0);
    	
    }
    
    /** Called when we click ACTIVATE button.Starting the Service(alarm) */
    public void startAlarm(){
    	//strating the service
    	Intent serviceIntent = new Intent(this,TravalService.class);
    	serviceIntent.putExtra("longitude", lon);
    	serviceIntent.putExtra("latitude", lat);
    	serviceIntent.putExtra("radius", Float.parseFloat(radius));
    	serviceIntent.putExtra("notification",alertType.getSelectedItemPosition());
    	
    	startService(serviceIntent);
    	
    }
    
    /** Called when we click DEACTIVATE button.Stoping the Service(alarm)) */
    public void stopAlarm(){
    	// Stop a service using the service name.
    	stopService(new Intent(this, TravalService.class));
    	
    	// clear notifiaction
    	cancelNotification();
    		
    	    	
    }
    
    /** Show alert dialog with appropriate message. */ 
    public void alertDialog(){
    	
    	String title = "Warning";
    	String message = "You need to select LOCATION and RADIUS";
    	String button1String = "OK";
    	AlertDialog.Builder ad = new AlertDialog.Builder(this);
    	ad.setTitle(title);
    	ad.setMessage(message);
    	ad.setPositiveButton(button1String,new OnClickListener() {
    		public void onClick(DialogInterface dialog,int arg1) {
    		}
    	});
    	ad.show();
    }
    
    /** cancel Traval Notification with ID=111 */
    public void cancelNotification(){
    	   	
    	//reference to notification manager
    	NotificationManager notificationManager;
    	notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	notificationManager.cancel(111);
    }
}